#!/usr/bin/env python
"""
TerminalReporter - Displays test suite results to the terminal (command prompt)

License: BSD
Project homepage: http://skaffold.sf.net
"""

import re
from skaffold import Reporter, Result
        
def wrap(string, indent_level=0, width=80):
    if type(string) is list:
        lines = map(lambda line: self.wrap(line, width), string)
    else:
        word_break = r"(?:[ \t\f\v]+\n?|$\n?)"
        full_line = r"(.{1,%d})" % (width)
        
        break_line = re.compile("%(full_line)s%(word_break)s|"
                                "%(full_line)s" 
                                % {'full_line':full_line, 'word_break':word_break},
                                re.MULTILINE)
        matches = break_line.findall(string)
        lines = map(lambda x: "".join(x), matches)
    indented = map(lambda line: " "*indent_level + line, lines)
    return '\n'.join(indented)

class TerminalReporter(Reporter):
    """A Reporter that displays back to the terminal."""
    def open(self):
        self.stats = dict()
        print "-"*70
        print "RUNNING SUITE:"
        print "-"*70
    def close(self):
        print "-"*70
        print " SUMMARY:"
        total = 0
        for k,v in sorted(self.stats.items()):  # get total to calculate percent
            total += v
        for k,v in sorted(self.stats.items()):
            print "    %8s: %3d%%  (%d tests)" % (k, v*100/total, v)
        print
    def report(self, result, tree):
        if not isinstance(result, Result):
            raise TypeError("Reporter's only know how to process Result exception types")

        # Report this result
        name = ".".join(tree)

        print
        print wrap("%s:" % name, 2)
        print wrap("[ %s ] %s" % (result.key, result.message), 4)
        if hasattr(result, 'traceback') and result.failed and not result.ran:
            print _wrap(result.traceback, 8)
            
        try:
            self.stats[result.key] += 1
        except KeyError:
            self.stats[result.key] = 1
